// components/select-page/index.js

import { Target, HttpUtil, Toast } from '../../utils/http_util.js'
import { camelCase } from '../../utils/util.js'
import { ServiceName, callService, removeService } from '../../utils/store.js'

Page({
  data: {
    valueKey: 'item_text',
    disableSearch: false,
    dataList: [],
    formData: {},
  },

  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: options.title? decodeURIComponent(options.title) : '请选择...',
    });

    let formData = Object.assign({}, options);
    delete formData.title;
    delete formData.valueKey;
    delete formData.title;
    delete formData.disableSearch;
    this.setData({
      valueKey: options.valueKey || 'item_text',
      formData: formData,
      regionId: wx.getStorageSync('userJob').region_id,
      disableSearch: options.disableSearch == 'true' ? true : false
    });

    this.fetchData();
  },

  onUnload() {
    removeService(ServiceName.selectPageRequestFuncCallback)
  },

  fetchData(serarch) {
    let param = Object.assign({}, this.data.formData)
    param.ticket = HttpUtil.ticket

    param.regionId = this.data.regionId;
    param.search = serarch || ''
    //如果selectPageRequestFuncCallback存在时，调用此方法获取接口数据(param, callback(dataList))
    let ret = callService(ServiceName.selectPageRequestFuncCallback, param, dataList => {
      if (!dataList.length) {
        Toast.message('暂无数据')
      }
      this.setData({
        dataList: dataList
      })
    })
    if(!ret) {
      Toast.showLoading()
      HttpUtil.get(Target.self, '/comtag/selectComTagDataList.action', param).then(res => {
        console.log(res)
        if (!res.data.data_list.length) {
          Toast.message('暂无数据')
        }
        this.setData({
          dataList: res.data.data_list
        })
      })
    }
  },

  searchChanged(e) {
    this.fetchData(e.detail)
  },

  itemClicked(e) {
    let item = e.currentTarget.dataset.item
    let ret = {}
    for (let key in item) {
      ret[camelCase(key)] = item[key]
    }
    delete ret.bssOrgId
    delete ret.bssOrgName
    callService(ServiceName.selectPageCallback, ret)
    wx.navigateBack()
  }
})